import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';


//预付卡控制器
class PrePaymentCardController extends BaseController{

  int page = 1;

  bool hasNextPage = false;
  ///订单列表
  List cardList = [];
  ///预付卡卡号
  TextEditingController cardNumCtr = TextEditingController();
  ///预付卡密码
  TextEditingController password = TextEditingController();


  @override
  void onInit() {
    getCardList();
    super.onInit();
  }

  //获取预付卡列表
  getCardList(){
    Tools.showLoading();
    Network.getPrepaymentCardList(page,5).then((value){
      // print("预付卡返回：$value");
      if(value==null){
        hasNextPage = false;
        cardList = [];
      }else{
        hasNextPage = value['hasNextPage'];
        if(page==1){
          cardList = value['list']??[];
        }else{
          cardList.addAll(value['list']);
        }
      }
      update();
      Tools.hideLoading();
    }).catchError((error){
      Tools.hideLoading();
    });
  }

  
  //添加预付卡
  void add(){
    if(cardNumCtr.text==''){
      Tools.showToast("请先输入预付卡卡号");
      return;
    }
    if(password.text==''){
      Tools.showToast("请输入预付卡密码");
      return;
    }
    Tools.showLoading();
    Network.addPrepaymentCard(cardNumCtr.text,password.text).then((value){
      if(value){
        Tools.showToast("绑定成功");
        getCardList();
        cardNumCtr.text = '';
        password.text = '';
        Get.back();
      }
      update();
      Tools.hideLoading();
    }).catchError((error){
      Tools.hideLoading();
    });
  }

  //删除预付卡
  void delete(int id){
    Tools.showModal(content: "确定要删除该预付卡么?",onCancel: (tag) => {},onConfirm: (tag) {
      Tools.showLoading();
      Network.delPrepaymentCard(id).then((value){
        if(value){
          Tools.showToast("删除成功");
          onPageRefresh();
          update();
        }
        Tools.hideLoading();
      }).catchError((error){
        Tools.hideLoading();
      });
      SmartDialog.dismiss(tag: tag);
    },);    
  }


  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page = 1;
    getCardList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading()async {
    if(hasNextPage==true){
      super.onPageLoading();
      page += 1;
      getCardList();
      baseRefreshCtr.loadComplete();
    }
  }


  @override
  void onClose() {
    super.onClose();
  }

}